package com.ys.zero.web;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.ys.zero.bean.Result;
import com.ys.zero.bean.User;
import com.ys.zero.biz.BizException;
import com.ys.zero.dao.UserDao;


@WebServlet("/submit.s")
public class SubmitServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
   
	//用户点击提交后执行方法， 作用： 将用户的头像 写入数据库
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//设置编码集
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		ServletContext context = getServletContext();
		String imagesPath = (String)context.getAttribute("imagesPath");
//		System.out.println("imagesPath:"+imagesPath);
		if(imagesPath == null) {
			String json  = new Gson().toJson(new Result(0,"头像选择不能为空"));
			response.getWriter().append(json);
			return ; 			
		}
		User user = (User)request.getSession().getAttribute("loginedUser");
		UserDao udao = new UserDao();
		try {
//			System.out.println(imagesPath);
			udao.updateimage(imagesPath, user.getAccount());
		} catch (BizException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
		}
		
		//修改会话里面的信息，实现头像实时更新
		user.setImage(imagesPath);
//		System.out.println(user);
		String json = new Gson().toJson(new Result(1,"更改头像成功"));
		response.getWriter().append(json);
	}


	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
